from pathlib import Path

from office import pdf
from traceback import format_exc
from ...base import ThreadBase


class EnOrDeCryptThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.columnValues = None
        self.is_encrypt = None
        self.is_decrypt = None
        self.password = None
        self.save_path = None

    def run(self):
        try:
            if self.is_decrypt is True and self.is_encrypt is False:
                for value in self.columnValues:
                    save_path = Path(self.save_path) / f'{Path(value).stem.replace("（加密）", "")}(解密).pdf'
                    pdf.decrypt4pdf(value, self.password, save_path)
            elif self.is_encrypt is True and self.is_decrypt is False:
                for value in self.columnValues:
                    pdf.encrypt4pdf(value, self.password, self.save_path)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, columnValues: list, is_encrypt: bool, is_decrypt: bool, password: str, save_path: str):
        self.columnValues = columnValues
        self.is_encrypt = is_encrypt
        self.is_decrypt = is_decrypt
        self.password = password
        self.save_path = save_path


class MergeToPdfThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.files = []
        self.save_path = None

    def run(self):
        try:
            pdf.merge2pdf(self.files, self.save_path)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, files, save_path):
        self.files = files
        self.save_path = save_path


class PdfToWordThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.file_path = None
        self.output_path = None

    def run(self):
        try:
            pdf.pdf2docx(self.file_path, self.output_path)
        except Exception as e:
            self.error.emit(format_exc())

    def set_value(self, file_path: str, output_path: str):
        self.file_path = file_path
        self.output_path = output_path


class TxtToPdfThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.files = []
        self.save_path = None

    def run(self):
        try:
            for file in self.files:
                pdf.txt2pdf(path=file, output_path=self.save_path)
        except Exception as e:
            print(format_exc())
            self.error.emit(format_exc())

    def set_value(self, files: list, save_path: str):
        self.files = files
        self.save_path = save_path


class PdfToImgThread(ThreadBase):
    def __init__(self, parent=None):
        super().__init__(parent)

    def run(self):
        pdf.pdf2imgs()

    def set_value(self, data: list, save_path: str):
        self.data = data
        self.save_path = data
